import React, { useState, useEffect } from 'react';
import {
    Card, Table, Button, Space, Input, Select,
    Tag, Avatar, App,
    Row, Col, Statistic, Typography, Divider,
    Alert
} from 'antd';
import {
    UserOutlined, PlusOutlined,
    TeamOutlined, UserAddOutlined, CrownOutlined,
    DownloadOutlined, SyncOutlined, FilterOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import axios from 'axios';
import UserCreateModal from './UserCreateModal';
import UserEditModal from './UserEditModal';
import UserDetailDrawer from './UserDetailDrawer';
import { useAdminStats } from '../../contexts/AdminStatsContext';
import { getFullMediaUrl } from '../../utils/config';

const { Search } = Input;
const { Option } = Select;
const { Text } = Typography;

interface User {
    id: number;
    username: string;
    email: string;
    is_staff: boolean;
    is_active: boolean;
    is_superuser: boolean;
    last_login: string;
    date_joined: string;
    profile: {
        avatar: string;
        nfc_card_id: string;
    };
    face_data_registered: boolean;
    access_logs_count: number;
}



const UserManagement: React.FC = () => {
    const { message, notification, modal } = App.useApp();
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState(false);

    // 使用全局统计数据Context
    const { stats, updateStatsAfterUserOperation } = useAdminStats();
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 5,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    });
    
    // 过滤和搜索状态
    const [filters, setFilters] = useState<{
        search: string;
        is_staff: boolean | undefined;
        is_active: boolean | undefined;
        has_face_data: boolean | undefined;
        has_nfc_card: boolean | undefined;
        date_range: any;
    }>({
        search: '',
        is_staff: undefined,
        is_active: undefined,
        has_face_data: undefined,
        has_nfc_card: undefined,
        date_range: null,
    });
    
    // 模态框和抽屉状态
    const [createModalVisible, setCreateModalVisible] = useState(false);
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);

    // 获取用户列表
    const fetchUsers = async (page = 1, pageSize = 20) => {
        setLoading(true);
        const token = localStorage.getItem('adminAuthToken');
        
        try {
            const params = new URLSearchParams({
                page: page.toString(),
                page_size: pageSize.toString(),
                ordering: '-date_joined',
            });
            
            // 添加过滤参数
            if (filters.search) params.append('search', filters.search);
            if (filters.is_staff !== undefined) params.append('is_staff', filters.is_staff.toString());
            if (filters.is_active !== undefined) params.append('is_active', filters.is_active.toString());
            if (filters.has_face_data !== undefined) params.append('has_face_data', filters.has_face_data.toString());
            if (filters.has_nfc_card !== undefined) params.append('has_nfc_card', filters.has_nfc_card.toString());
            
            const response = await axios.get(`/api/admin/users/?${params}`, {
                headers: { 'Authorization': `Token ${token}` }
            });
            
            setUsers(response.data.results);
            setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize,
                total: response.data.count,
            }));
            
            // 更新统计信息（现在由Context管理）
            // 统计信息会通过Context自动更新
            
        } catch (error) {
            console.error('Failed to fetch users:', error);
            message.error('获取用户列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 统计信息现在由Context管理，无需本地fetchStats函数

    // 初始化加载
    useEffect(() => {
        const loadData = async () => {
            try {
                await fetchUsers();
                // 统计数据由Context管理，会自动加载
            } catch (error) {
                console.error('Failed to load initial data:', error);
                message.error('加载数据失败，请刷新页面重试');
            }
        };
        loadData();
    }, []);

    // 当过滤条件改变时重新加载
    useEffect(() => {
        const loadFilteredData = async () => {
            try {
                await fetchUsers(1, pagination.pageSize);
            } catch (error) {
                console.error('Failed to load filtered data:', error);
            }
        };
        loadFilteredData();
    }, [filters.search, filters.is_staff, filters.is_active, filters.has_face_data, filters.has_nfc_card]);

    // 删除用户
    const handleDeleteUser = async (userId: number, username: string) => {
        const token = localStorage.getItem('adminAuthToken');

        try {
            await axios.delete(`/api/admin/users/${userId}/delete/`, {
                headers: { 'Authorization': `Token ${token}` }
            });

            // 显示成功通知
            notification.success({
                message: '用户删除成功',
                description: `用户 "${username}" 已被成功删除`,
                placement: 'topRight',
                duration: 4,
            });

            fetchUsers(pagination.current, pagination.pageSize);
            updateStatsAfterUserOperation();
        } catch (error: any) {
            const errorMsg = error.response?.data?.error || '删除用户失败';

            // 显示错误通知
            notification.error({
                message: '删除用户失败',
                description: errorMsg,
                placement: 'topRight',
                duration: 6,
            });
        }
    };

    // 批量操作
    const handleBatchAction = async (action: string) => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要操作的用户');
            return;
        }

        const token = localStorage.getItem('adminAuthToken');

        // 操作名称映射
        const actionNames = {
            'activate': '激活',
            'deactivate': '停用',
            'make_staff': '设为管理员',
            'remove_staff': '取消管理员',
            'delete': '删除'
        };

        const actionName = actionNames[action as keyof typeof actionNames] || action;

        try {
            const response = await axios.post('/api/admin/users/batch/', {
                user_ids: selectedRowKeys,
                action: action
            }, {
                headers: { 'Authorization': `Token ${token}` }
            });

            const result = response.data;

            // 显示详细的成功通知
            notification.success({
                message: '批量操作完成',
                description: `${actionName}操作完成：成功 ${result.success_count} 个，总计 ${result.total_count} 个用户`,
                placement: 'topRight',
                duration: 5,
            });

            // 如果有失败的用户，显示警告
            if (result.failed_users && result.failed_users.length > 0) {
                notification.warning({
                    message: '部分操作失败',
                    description: `以下用户操作失败：${result.failed_users.join(', ')}`,
                    placement: 'topRight',
                    duration: 8,
                });
            }

            setSelectedRowKeys([]);
            fetchUsers(pagination.current, pagination.pageSize);
            updateStatsAfterUserOperation();
        } catch (error: any) {
            const errorMsg = error.response?.data?.error || '批量操作失败';

            notification.error({
                message: '批量操作失败',
                description: `${actionName}操作失败：${errorMsg}`,
                placement: 'topRight',
                duration: 6,
            });
        }
    };

    // 导出用户数据
    const handleExportUsers = async () => {
        const token = localStorage.getItem('adminAuthToken');

        try {
            // 获取所有用户数据
            const response = await axios.get('/api/admin/users/?page_size=1000', {
                headers: { 'Authorization': `Token ${token}` }
            });

            const users = response.data.results;

            // 准备CSV数据
            const csvData = users.map((user: User) => ({
                '用户名': user.username,
                '邮箱': user.email,
                '状态': user.is_active ? '活跃' : '停用',
                '权限': user.is_superuser ? '超级管理员' : (user.is_staff ? '管理员' : '普通用户'),
                'NFC卡号': user.profile?.nfc_card_id || '',
                '人脸数据': user.face_data_registered ? '已注册' : '未注册',
                '访问次数': user.access_logs_count,
                '注册时间': new Date(user.date_joined).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                }),
                '最后登录': user.last_login ? new Date(user.last_login).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                }) : '从未登录'
            }));

            // 转换为CSV格式
            const headers = Object.keys(csvData[0]);
            const csvContent = [
                headers.join(','),
                ...csvData.map((row: any) => headers.map(header => `"${row[header as keyof typeof row]}"`).join(','))
            ].join('\n');

            // 下载文件
            const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `用户数据_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            notification.success({
                message: '导出成功',
                description: `已导出 ${users.length} 个用户的数据`,
                placement: 'topRight',
                duration: 3,
            });

        } catch (error) {
            console.error('Failed to export users:', error);
            notification.error({
                message: '导出失败',
                description: '无法导出用户数据，请稍后重试',
                placement: 'topRight',
                duration: 5,
            });
        }
    };

    // 刷新数据
    const handleRefresh = async () => {
        notification.info({
            message: '正在刷新数据',
            description: '正在重新加载用户列表和统计信息...',
            placement: 'topRight',
            duration: 2,
        });

        try {
            await fetchUsers(pagination.current, pagination.pageSize);
            updateStatsAfterUserOperation();

            notification.success({
                message: '刷新完成',
                description: '用户数据已更新到最新状态',
                placement: 'topRight',
                duration: 3,
            });
        } catch (error) {
            notification.error({
                message: '刷新失败',
                description: '无法刷新数据，请检查网络连接',
                placement: 'topRight',
                duration: 5,
            });
        }
    };

    // 表格列定义
    const columns: ColumnsType<User> = [
        {
            title: '用户',
            key: 'user',
            width: 200,
            render: (_, record) => (
                <Space>
                    <Avatar
                        src={getFullMediaUrl(record.profile?.avatar)}
                        icon={<UserOutlined />}
                        size="small"
                    />
                    <div>
                        <div style={{ fontWeight: 500 }}>{record.username || 'N/A'}</div>
                        <div style={{ fontSize: 12, color: '#666' }}>
                            {record.email || 'N/A'}
                        </div>
                    </div>
                </Space>
            ),
        },
        {
            title: '状态',
            key: 'status',
            width: 120,
            render: (_, record) => (
                <Space direction="vertical" size={2}>
                    <Tag color={record.is_active ? 'green' : 'red'}>
                        {record.is_active ? '活跃' : '停用'}
                    </Tag>
                    {record.is_staff && (
                        <Tag color="blue" icon={<CrownOutlined />}>
                            {record.is_superuser ? '超级管理员' : '管理员'}
                        </Tag>
                    )}
                </Space>
            ),
        },
        {
            title: '人脸数据',
            key: 'face_data',
            width: 100,
            render: (_, record) => (
                <span>{record.face_data_registered ? '已注册' : '未注册'}</span>
            ),
        },
        {
            title: 'NFC卡',
            key: 'nfc_card',
            width: 100,
            render: (_, record) => (
                <span>{record.profile?.nfc_card_id ? '已绑定' : '未绑定'}</span>
            ),
        },
        {
            title: '访问次数',
            dataIndex: 'access_logs_count',
            key: 'access_logs_count',
            width: 100,
            sorter: true,
        },
        {
            title: '注册时间',
            dataIndex: 'date_joined',
            key: 'date_joined',
            width: 140,
            sorter: true,
            render: (date) => {
                const dateObj = new Date(date);
                return dateObj.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            },
        },
        {
            title: '最后登录',
            dataIndex: 'last_login',
            key: 'last_login',
            width: 140,
            render: (date) => {
                if (!date) return '从未登录';
                const dateObj = new Date(date);
                return dateObj.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            },
        },
        {
            title: '操作',
            key: 'actions',
            width: 150,
            render: (_, record) => (
                <Space size="small">
                    <Button
                        type="text"
                        size="small"
                        onClick={() => {
                            setSelectedUser(record);
                            setDetailDrawerVisible(true);
                        }}
                    >
                        详情
                    </Button>
                    <Button
                        type="text"
                        size="small"
                        onClick={() => {
                            setSelectedUser(record);
                            setEditModalVisible(true);
                        }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="text"
                        size="small"
                        danger
                        onClick={() => {
                            modal.confirm({
                                title: '确认删除用户',
                                content: (
                                    <div>
                                        <p>确定要删除用户 <strong>"{record.username}"</strong> 吗？</p>
                                        <p style={{ color: '#ff4d4f', fontSize: '12px' }}>
                                            ⚠️ 此操作不可恢复，将同时删除用户的所有相关数据
                                        </p>
                                    </div>
                                ),
                                okText: '确认删除',
                                okType: 'danger',
                                cancelText: '取消',
                                onOk: async () => {
                                    await handleDeleteUser(record.id, record.username);
                                },
                            });
                        }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    // 如果正在加载且没有数据，显示加载状态
    if (loading && users.length === 0) {
        return (
            <div style={{ textAlign: 'center', padding: '50px' }}>
                <div>加载中...</div>
            </div>
        );
    }

    return (
        <div>
            {/* 统计卡片 - 始终显示，避免加载时闪烁 */}
            <Row gutter={16} style={{ marginBottom: 24 }}>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="总用户数"
                            value={stats?.user_counts?.total || 0}
                            prefix={<TeamOutlined />}
                            valueStyle={{ color: '#1890ff' }}
                            loading={!stats}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="活跃用户"
                            value={stats?.user_counts?.active || 0}
                            prefix={<UserOutlined />}
                            valueStyle={{ color: '#52c41a' }}
                            loading={!stats}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="管理员"
                            value={stats?.user_counts?.staff || 0}
                            prefix={<CrownOutlined />}
                            valueStyle={{ color: '#fa8c16' }}
                            loading={!stats}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="本周新增"
                            value={stats?.registration_trends?.new_this_week || 0}
                            prefix={<UserAddOutlined />}
                            valueStyle={{ color: '#722ed1' }}
                            loading={!stats}
                        />
                    </Card>
                </Col>
            </Row>

            {/* 主要内容卡片 */}
            <Card>
                {/* 工具栏 */}
                <div style={{ marginBottom: 16 }}>
                    <Row gutter={16} align="middle">
                        <Col flex="auto">
                            <Space size="middle">
                                <Search
                                    placeholder="搜索用户名、邮箱或姓名"
                                    allowClear
                                    style={{ width: 300 }}
                                    onSearch={(value) => setFilters({ ...filters, search: value })}
                                />

                                <Select
                                    placeholder="用户状态"
                                    allowClear
                                    style={{ width: 120 }}
                                    onChange={(value) => setFilters({ ...filters, is_active: value })}
                                >
                                    <Option value={true}>活跃</Option>
                                    <Option value={false}>停用</Option>
                                </Select>

                                <Select
                                    placeholder="权限级别"
                                    allowClear
                                    style={{ width: 120 }}
                                    onChange={(value) => setFilters({ ...filters, is_staff: value })}
                                >
                                    <Option value={true}>管理员</Option>
                                    <Option value={false}>普通用户</Option>
                                </Select>

                                <Select
                                    placeholder="人脸数据"
                                    allowClear
                                    style={{ width: 120 }}
                                    onChange={(value) => setFilters({ ...filters, has_face_data: value })}
                                >
                                    <Option value={true}>已注册</Option>
                                    <Option value={false}>未注册</Option>
                                </Select>

                                <Button
                                    icon={<FilterOutlined />}
                                    onClick={() => {
                                        setFilters({
                                            search: '',
                                            is_staff: undefined,
                                            is_active: undefined,
                                            has_face_data: undefined,
                                            has_nfc_card: undefined,
                                            date_range: null,
                                        });
                                        fetchUsers(1, pagination.pageSize);
                                        message.success('筛选条件已重置');
                                    }}
                                >
                                    重置筛选
                                </Button>

                                <Button
                                    icon={<SyncOutlined />}
                                    onClick={handleRefresh}
                                >
                                    刷新数据
                                </Button>
                            </Space>
                        </Col>

                        <Col>
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<PlusOutlined />}
                                    onClick={() => setCreateModalVisible(true)}
                                >
                                    新增用户
                                </Button>

                                <Button
                                    icon={<DownloadOutlined />}
                                    onClick={handleExportUsers}
                                >
                                    导出CSV
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </div>

                {/* 批量操作工具栏 */}
                {selectedRowKeys.length > 0 && (
                    <div style={{
                        marginBottom: 16,
                        padding: 12,
                        background: '#f0f2f5',
                        borderRadius: 6
                    }}>
                        <Space>
                            <Text>已选择 {selectedRowKeys.length} 项</Text>
                            <Divider type="vertical" />
                            <Button
                                size="small"
                                onClick={() => handleBatchAction('activate')}
                            >
                                批量激活
                            </Button>
                            <Button
                                size="small"
                                onClick={() => handleBatchAction('deactivate')}
                            >
                                批量停用
                            </Button>
                            <Button
                                size="small"
                                onClick={() => handleBatchAction('make_staff')}
                            >
                                设为管理员
                            </Button>
                            <Button
                                size="small"
                                onClick={() => handleBatchAction('remove_staff')}
                            >
                                取消管理员
                            </Button>
                            <Button
                                size="small"
                                danger
                                onClick={() => {
                                    modal.confirm({
                                        title: '确认批量删除用户',
                                        content: (
                                            <div>
                                                <p>确定要删除选中的 <strong>{selectedRowKeys.length}</strong> 个用户吗？</p>
                                                <Alert
                                                    message="危险操作警告"
                                                    description="此操作将永久删除所有选中用户及其相关数据，包括人脸数据、访问记录等，且无法恢复！"
                                                    type="error"
                                                    showIcon
                                                    style={{ marginTop: 12 }}
                                                />
                                            </div>
                                        ),
                                        okText: '确认删除',
                                        okType: 'danger',
                                        cancelText: '取消',
                                        width: 500,
                                        onOk: async () => {
                                            await handleBatchAction('delete');
                                        },
                                    });
                                }}
                            >
                                批量删除
                            </Button>
                            <Button
                                size="small"
                                onClick={() => setSelectedRowKeys([])}
                            >
                                取消选择
                            </Button>
                        </Space>
                    </div>
                )}

                {/* 用户表格 */}
                <Table
                    columns={columns}
                    dataSource={users}
                    rowKey="id"
                    loading={loading}
                    pagination={pagination}
                    rowSelection={{
                        selectedRowKeys,
                        onChange: setSelectedRowKeys,
                        getCheckboxProps: (record) => ({
                            disabled: record.is_superuser, // 禁止选择超级管理员
                        }),
                    }}
                    onChange={(paginationInfo, filters, sorter) => {
                        const { current, pageSize } = paginationInfo;
                        // 当页码或每页数量变化时，重新获取数据
                        if (current !== pagination.current || pageSize !== pagination.pageSize) {
                            fetchUsers(current, pageSize);
                        }
                        
                        // 如果需要处理排序和过滤，可以在这里添加逻辑
                    }}
                    scroll={{ x: 1200 }}
                />
            </Card>

            {/* 创建用户模态框 */}
            <UserCreateModal
                visible={createModalVisible}
                onCancel={() => setCreateModalVisible(false)}
                onSuccess={() => {
                    setCreateModalVisible(false);
                    fetchUsers(pagination.current, pagination.pageSize);
                    updateStatsAfterUserOperation();
                }}
            />

            {/* 编辑用户模态框 */}
            <UserEditModal
                visible={editModalVisible}
                user={selectedUser}
                onCancel={() => {
                    setEditModalVisible(false);
                    setSelectedUser(null);
                }}
                onSuccess={() => {
                    setEditModalVisible(false);
                    setSelectedUser(null);
                    fetchUsers(pagination.current, pagination.pageSize);
                    updateStatsAfterUserOperation();
                }}
            />

            {/* 用户详情抽屉 */}
            <UserDetailDrawer
                visible={detailDrawerVisible}
                user={selectedUser}
                onClose={() => {
                    setDetailDrawerVisible(false);
                    setSelectedUser(null);
                }}
            />
        </div>
    );
};

export default UserManagement;
